#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Denis Kürov
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/copyleft/gpl.txt.

# Create your views here.
from forms.fireform import IpDropForm,UdpForm,TcpForm,ExtraForm,IcmpForm,PrefixForm,LogSearchForm,ChainForm 
from django.shortcuts import render_to_response,get_object_or_404
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from models import Rule,Udp,Tcp,Optional,Icmp,Prefixer,Logs,Chain,Loadindex
from dbwork.ruleorder import RuleLoadOrder
from dbwork.rulegen import RuleGenerator,IptablesRunner
from dbwork.logger import Logman
from django.template.context import RequestContext
from forms.fireutil import FireUtils
from django.views.generic.list_detail import object_list
from django.utils.datastructures import MultiValueDict
from django.contrib.auth.decorators import login_required

@login_required
def add_rule(request,rule_id=None):
    """ Adding a new rule form is that one and also updater"""
    #some buggy values :
    if request.method == 'POST':
        #if it is an edit
        if rule_id:
            rule_edit = get_object_or_404(Rule, pk=rule_id)
            #for future use we need that to know what to do
            yuklu_ise=rule_edit.loaded
        
        poster=request.POST.copy()
        if not poster.has_key('kaynak_ip_2'):
            poster.appendlist('kaynak_ip_2',False)
        
        if not poster.has_key('hedef_ip_2'):
            poster.appendlist('hedef_ip_2',False)
            
        if not poster.has_key('yukle_1'):
            poster.appendlist('yukle_1',False)
            
        if not poster.has_key('kaynak_aygit'):
            poster.appendlist('kaynak_aygit','any')
        
        if not poster.has_key('hedef_aygit'):
            poster.appendlist('hedef_aygit','any')
        
        #kaynak_aygit
        #hedef_aygit
            
        #print poster
        form = IpDropForm(poster)
        
        if form.is_valid():
            # Control if the rule already exists
            #if it is not an edit and if we try to add a one with same name
            if not rule_id:
                exist=Rule.objects.filter(name=poster['name'])
                
                if exist:
                    return render_to_response('add.html', {'form': form,'hatalar':'Kural zaten var!'})
                
            #create the rule instance to add it to the database for now diyelim o zaman yani...
            if poster['kaynak_ip_2']:
                k_ip=",".join([poster['kaynak_ip_0'],'!',poster['kaynak_ip_1']])
            else:
                k_ip=",".join([poster['kaynak_ip_0'],poster['kaynak_ip_1']])
            
            #for destination ip part
            if poster['hedef_ip_2']:
                h_ip=",".join([poster['hedef_ip_0'],'!',poster['hedef_ip_1']])
            else:
                h_ip=",".join([poster['hedef_ip_0'],poster['hedef_ip_1']])
            #it indicate is if the 
            loder=False
            
            #the order class
            rl=RuleLoadOrder()
            
            if poster['yukle_1']:
                loder=True
            
            if not rule_id :
                r=Rule(parent_chain_id=poster['zincir'],parent_target_id=poster['eylem'],name=poster['name'],
                       sip=k_ip,dip=h_ip,s_interface=poster['kaynak_aygit'],d_interface=poster['hedef_aygit'],loaded=loder)
            
            else:
                
                rule_edit.parent_chain_id=poster['zincir']
                rule_edit.parent_target_id=poster['eylem']
                rule_edit.name=poster['name']
                rule_edit.sip=k_ip
                rule_edit.dip=h_ip
                rule_edit.s_interface=poster['kaynak_aygit']
                rule_edit.d_interface=poster['hedef_aygit']
                rule_edit.loaded=loder
                
            try:
                #it is important if it is edit or add
                if not rule_id:
                    r.save()
                else:
                    rule_edit.save()
                    #burada iste flushh olacak
                    IptablesRunner.flush_signal()
                
                #if it should be loaded immediately to iptables memory...
                if poster['yukle_1']:
                    
                    if not rule_id:
                        o=rl.insert_order(r.id,ordernum=poster['yukle_0'])
                        
                    else:
                        o=rl.insert_order(rule_edit.id,ordernum=poster['yukle_0'])
                    
                #else:
                    #if it is a edit operation
                #    if rule_id and yuklu_ise:
                        #onceden de aktif olmasi gerekir yoksa bisi yapmaya gerek yok
                        #yep it must be done
                #        rl.delete_order(rule_edit.id)
                
            except Exception,e:
                print e
                if not rule_id:
                    return render_to_response('add.html', {'form': form,'hatalar':'Kural kaydederken hata'})
                else:
                    return render_to_response('add.html', {'form': form,'hatalar':'Kural kaydederken hata','rule_id':rule_id})
            #on succesfull adding go there yooo
            
            chain_name=None
            return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.show_sort_chains"))
            
    else:
        form = IpDropForm()
    
    #the final render is here...
    if not rule_id:   
        return render_to_response('add.html', {'form': form})
    else:
        #if it is an edit form
        return render_to_response('add.html', {'form': form,'rule_id':rule_id})

@login_required
def index(request):
    """ The default page to be shown"""
    #print request.build_absolute_uri()
    return render_to_response('index.html')

@login_required
def add_udp(request,rule_id,udp_id=None):
    """" That one is adding a rule to the Udp part sport,dport here udp_id is for better performance"""
    #control if it is there you may not have a rule like that
    r = get_object_or_404(Rule, pk=rule_id)
    
    if request.method=='GET':
        if r.udp_set.count()!=0 or r.tcp_set.count()!=0 or r.icmp_set.count()!=0:
            request.flash['error']="Udp,Tcp,Icmp sadece bir tane olabilir!"
            return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
    
    if request.method == 'POST':
        
        if udp_id:
            if r.udp_set.count()==0:
                request.flash['error']="Olmayan udp editlenemez"
                return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
            
            else:
                
                udp_edit = get_object_or_404(Udp,parent_rule=rule_id)
        
        poster=request.POST.copy()
        if not poster.has_key('kaynak_port_2'):
            poster.appendlist('kaynak_port_2',False)
        
        if not poster.has_key('hedef_port_2'):
            poster.appendlist('hedef_port_2',False)
            
        form=UdpForm(poster)
        
        if form.is_valid():
            #henuz nere gitcek karar vermedim ya be
            if poster['kaynak_port_2']:
                
                k_port="*".join([poster['kaynak_port_0'],'!',poster['kaynak_port_1']])
            else:
                k_port="*".join([poster['kaynak_port_0'],poster['kaynak_port_1']])
                
            if poster['hedef_port_2']:
                
                h_port="*".join([poster['hedef_port_0'],'!',poster['hedef_port_1']])
            else:
                h_port="*".join([poster['hedef_port_0'],poster['hedef_port_1']])
            
            if not udp_id: 
                u=Udp(parent_rule_id=rule_id,sport=k_port,dport=h_port)
            else:
                udp_edit.sport=k_port
                udp_edit.dport=h_port
            
            try:
                if not udp_id:
                        
                    u.save()
                
                else:
                    udp_edit.save()
            
            except Exception,e:
                print "Hata var :",e
                h="Udp kaydederken hata cikti."
                if not udp_id:
                    return render_to_response('add_udp.html', {'form': form,'rule_id':rule_id,'hatalar':h})
                else:
                    return render_to_response('add_udp.html', {'form': form,'rule_id':rule_id,'hatalar':h,'udp_id':udp_id})
            
            #return HttpResponseRedirect(reverse("mysite.iptables.views.index"))
            return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
        
    else:
        form = UdpForm()
    
    #edit or not
    if not udp_id:
        #the final render is here...   
        return render_to_response('add_udp.html', {'form': form,'rule_id':rule_id})
    else:
        return render_to_response('add_udp.html', {'form': form,'rule_id':rule_id,'udp_id':udp_id})
        

@login_required
def rule_edit(request,rule_id):
    """ Displays the form filled in that case """
    #check if it exists
    r = get_object_or_404(Rule, pk=rule_id)
    
    rule_data={}
    
    rule_data['name']=r.name
    rule_data['zincir']=r.parent_chain_id
    rule_data['eylem']=r.parent_target_id
    
    ip=r.sip.split(',')
    
    rule_data['kaynak_ip_0']=ip[0]
    rule_data['kaynak_ip_1']=ip[len(ip)-1]
    
    if len(ip)==3:
        rule_data['kaynak_ip_2']=True
    else:
        rule_data['kaynak_ip_2']=False
        
    ip=r.dip.split(',')
    
    rule_data['hedef_ip_0']=ip[0]
    rule_data['hedef_ip_1']=ip[len(ip)-1]
    
    if len(ip)==3:
        rule_data['hedef_ip_2']=True
    else:
        rule_data['hedef_ip_2']=False
        
    
    rule_data['kaynak_aygit']=r.s_interface
    rule_data['hedef_aygit']=r.d_interface
    
    rule_data['yukle_1']=r.loaded
    
    #that part may change in the future should actually
    rule_data['yukle_0']='last'
    
    form = IpDropForm(rule_data)
    
    #the iptables syntax
    display_rule=None
    r_d=RuleGenerator()
    display_rule=r_d.create_rule(rule_id,'append')
    
    return render_to_response('add.html', {'form': form,'rule_id':rule_id,'d_rule':display_rule},context_instance=RequestContext(request))


@login_required
def edit_udp(request,rule_id):
    """ Displays a form for editing the udp's here """
    
    u = get_object_or_404(Udp,parent_rule=rule_id)
    
    udp_data={}
    
    port=u.sport.split('*')
    
    udp_data['kaynak_port_0']=port[0]
    udp_data['kaynak_port_1']=port[len(port)-1]
    
    if len(port)==3:
         udp_data['kaynak_port_2']=True
         
    else:
        udp_data['kaynak_port_2']=False
    
    port=u.dport.split('*')
    
    udp_data['hedef_port_0']=port[0]
    udp_data['hedef_port_1']=port[len(port)-1]
    
    if len(port)==3:
         udp_data['hedef_port_2']=True
         
    else:
        udp_data['hedef_port_2']=False
    
    form=UdpForm(udp_data)
    
    return render_to_response('add_udp.html', {'form': form,'rule_id':rule_id,'udp_id':u.id})


@login_required
def add_tcp(request,rule_id,tcp_id=None):
    """ That one adds a new tcp rule to the datbaase"""
    r = get_object_or_404(Rule, pk=rule_id)
    
    if request.method=='GET':
        if r.udp_set.count()!=0 or r.tcp_set.count()!=0 or r.icmp_set.count()!=0:
            request.flash['error']="Udp,Tcp,Icmp sadece bir tane olabilir!"
            return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
        
    if request.method == 'POST':
        
        if tcp_id:
            if r.tcp_set.count()==0:
                request.flash['error']="Olmayan tcp editlenemez"
                return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
            
            else:
                tcp_edit = get_object_or_404(Tcp,parent_rule=rule_id)
        
        poster=request.POST.copy()
        if not poster.has_key('kaynak_port_2'):
            poster.appendlist('kaynak_port_2',False)
        
        if not poster.has_key('hedef_port_2'):
            poster.appendlist('hedef_port_2',False)
            
        #if not poster.has_key('seter'):
        #    poster.appendlist('seter',[])
        
        #if not poster.has_key('comparer'):
        #    poster.appendlist('comparer',[])
            
        #print poster
        form=TcpForm(poster)
        
        
        
        if not FireUtils.control_flags(poster.getlist('comparer'),poster.getlist('seter')):
            if not tcp_id:
                return render_to_response('add_tcp.html', {'form': form,'rule_id':rule_id,'hatalar':"Tcp Flag Hatasi"})
            else:
                return render_to_response('add_tcp.html', {'form': form,'rule_id':rule_id,'hatalar':"Tcp Flag Hatasi",'tcp_id':tcp_id})
                
        if form.is_valid():
            #convert to format we need
            if poster['kaynak_port_2']:
                
                k_port="*".join([poster['kaynak_port_0'],'!',poster['kaynak_port_1']])
            else:
                k_port="*".join([poster['kaynak_port_0'],poster['kaynak_port_1']])
                
            if poster['hedef_port_2']:
                
                h_port="*".join([poster['hedef_port_0'],'!',poster['hedef_port_1']])
            else:
                h_port="*".join([poster['hedef_port_0'],poster['hedef_port_1']])
            #henuz nere gitcek karar vermedim ya be
            t_flag="0"
            
            if poster.has_key('comparer') and poster.has_key('seter'):
                t_flag=",".join(poster.getlist('comparer'))
                t_flag="".join([t_flag," ",",".join(poster.getlist('seter'))])
                #print t_flag
                
            if not tcp_id: 
                t=Tcp(parent_rule_id=rule_id,sport=k_port,dport=h_port,tcp_flag=t_flag)
            else:
                tcp_edit.sport=k_port
                tcp_edit.dport=h_port
                tcp_edit.tcp_flag=t_flag
            
            try:
                if not tcp_id:
                        
                    t.save()
                
                else:
                    tcp_edit.save()
            
            except Exception,e:
                print "Hata var :",e
                h="Tcp kaydederken hata cikti."
                if not tcp_id:
                    return render_to_response('add_tcp.html', {'form': form,'rule_id':rule_id,'hatalar':h})
                else:
                    return render_to_response('add_tcp.html', {'form': form,'rule_id':rule_id,'hatalar':h,'tcp_id':tcp_id})
                
            
            return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
            #return HttpResponseRedirect(reverse("mysite.iptables.views.index"))
        
        
    else:
        form = TcpForm()
    
    #edit or not
    if not tcp_id:
        #the final render is here...   
        return render_to_response('add_tcp.html', {'form': form,'rule_id':rule_id})
    else:
        return render_to_response('add_tcp.html', {'form': form,'rule_id':rule_id,'tcp_id':tcp_id})

@login_required
def edit_tcp(request,rule_id):
    """ Shows the dialog for tcp editing..."""
    t = get_object_or_404(Tcp,parent_rule=rule_id)
    
    tcp_data={}
    
    port=t.sport.split('*')
    
    tcp_data['kaynak_port_0']=port[0]
    tcp_data['kaynak_port_1']=port[len(port)-1]
    
    if len(port)==3:
         tcp_data['kaynak_port_2']=True
         
    else:
        tcp_data['kaynak_port_2']=False
    
    port=t.dport.split('*')
    
    tcp_data['hedef_port_0']=port[0]
    tcp_data['hedef_port_1']=port[len(port)-1]
    
    if len(port)==3:
         tcp_data['hedef_port_2']=True
         
    else:
        tcp_data['hedef_port_2']=False
    
    if t.tcp_flag=="0":    
        tcp_data['seter']=[]
        tcp_data['comparer']=[]
    else:
        flags=t.tcp_flag.split(" ")
        c_flag=flags[0].split(",")
        s_flag=flags[1].split(",")
        
        #print c_flag
        #print s_flag
        
        tcp_data['seter']=s_flag
        tcp_data['comparer']=c_flag
        
    form=TcpForm(tcp_data)
    
    return render_to_response('add_tcp.html', {'form': form,'rule_id':rule_id,'tcp_id':t.id})


@login_required
def add_extra(request,rule_id,extra_id=None):
    """ That is the view for -m options of the iptables rule set..."""
        #control if it is there you may not have a rule like that
    r = get_object_or_404(Rule, pk=rule_id)
    
    if request.method=='GET':
        if r.optional_set.count()!=0:
            request.flash['error']="Bir tane extra olabilir!"
            return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
    
    if request.method == 'POST':
        
        if extra_id:
            if r.optional_set.count()==0:
                request.flash['error']="Olmayan extra editlenemez"
                return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
            
            else:
                
                extra_edit = get_object_or_404(Optional,parent_rule=rule_id)
        
        poster=request.POST.copy()
        
        #print poster
        #burada choices ile ilgili sorun olursa eklnecek...
            
        form=ExtraForm(poster)
        
        if form.is_valid():
            #henuz nere gitcek karar vermedim ya be
            #burada formdan gelen degiskenler uygun hale getirilir
            form_data={}
            
            #durum var mi ?
            if poster.has_key('b_takip'):
                # if has a tick
                if poster.has_key('b_takip_c'):
                    form_data['b_takip']="*".join(['!',",".join(poster.getlist('b_takip'))])
                    
                else:
                    form_data['b_takip']=",".join(poster.getlist('b_takip'))
                    
            else:
                form_data['b_takip']="0"
                    
            
            if poster.has_key('b_durum'):
                # if has a tick
                if poster.has_key('b_durum_c'):
                    form_data['b_durum']="*".join(['!',",".join(poster.getlist('b_durum'))])
                    
                else:
                    form_data['b_durum']=",".join(poster.getlist('b_durum'))
            else:
                form_data['b_durum']="0"
                    
            #the packet limit situation
            if poster['p_limit']!='':
                if poster.has_key('p_limit_c'):
                    form_data['p_limit']="*".join(["!",poster['p_limit']])
                    
                else:
                    form_data['p_limit']=poster['p_limit']
                    
            else:
                form_data['p_limit']="0"
                
            #the mac situation
            if poster['mac']!='':
                if poster.has_key('mac_c'):
                    form_data['mac']="*".join(["!",poster['mac']])
                    
                else:
                    form_data['mac']=poster['mac']
                    
            else:
                form_data['mac']="0"
            
                
            if poster['limit']!='':
                if poster['burst']!='':
                    form_data['limit']="*".join([poster['burst'],"".join([poster['limit'],'/',poster['d_limit_select']])])
                    
                else:
                    form_data['limit']="".join([poster['limit'],'/',poster['d_limit_select']])
                    
            else:
                form_data['limit']="0"
            
            #it was done yep
            #print form_data
            
            
                
            #burada exception yakalama islemi olacak
            
            if not extra_id:
                extra=Optional(parent_rule_id=rule_id,
                               ctstaus=form_data['b_takip'],
                               mlength =form_data['p_limit'],
                               mlimit=form_data['limit'],
                               mac=form_data['mac'],
                               state=form_data['b_durum'])
            else:
                extra_edit.ctstaus=form_data['b_takip']
                extra_edit.mlength =form_data['p_limit']
                extra_edit.mlimit=form_data['limit']
                extra_edit.mac=form_data['mac']
                extra_edit.state=form_data['b_durum']
                
            try:
                if not extra_id:
                        
                    extra.save()
                
                else:
                    extra_edit.save()
            
            except Exception,e:
                print "Hata var :",e
                h="Extra kaydederken hata cikti."
                if not extra_id:
                    return render_to_response('add_extra.html', {'form': form,'rule_id':rule_id,'hatalar':h})
                else:
                    return render_to_response('add_extra.html', {'form': form,'rule_id':rule_id,'hatalar':h,'extra_id':extra_id})
                
                
            return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
            #return HttpResponseRedirect(reverse("mysite.iptables.views.index"))
        
        
    else:
        form = ExtraForm()
    
    #edit or not
    if not extra_id:
        #the final render is here...   
        return render_to_response('add_extra.html', {'form': form,'rule_id':rule_id})
    else:
        return render_to_response('add_extra.html', {'form': form,'rule_id':rule_id,'extra_id':extra_id})
    

@login_required
def edit_extra(request,rule_id):
    """ That one is for editing the extra options actuaally it just shows the screen for now"""
    
    e = get_object_or_404(Optional,parent_rule=rule_id)
    
    extra_data={}
    
    # b_takip sinamasi
    temp_data=e.ctstaus
    
    if temp_data=="0":
        extra_data['b_takip']=[]
        extra_data['b_takip_c']=False
        
    else:
        temp_data=temp_data.split("*")
        if len(temp_data)==2:
            extra_data['b_takip_c']=True
            temp_data=temp_data[1].split(",")
            extra_data['b_takip']=temp_data
            
        else:
            extra_data['b_takip_c']=False
            temp_data=temp_data[0].split(",")
            extra_data['b_takip']=temp_data
    
    #baglanti durum ctstate
    temp_data=e.state
    
    if temp_data=="0":
        extra_data['b_durum']=[]
        extra_data['b_durum_c']=False
        
    else:
        temp_data=temp_data.split("*")
        if len(temp_data)==2:
            extra_data['b_durum_c']=True
            temp_data=temp_data[1].split(",")
            extra_data['b_durum']=temp_data
            
        else:
            extra_data['b_durum_c']=False
            temp_data=temp_data[0].split(",")
            extra_data['b_durum']=temp_data
    
    
    #paket limit koyma make it custom yani
    temp_data=e.mlength
    
    if temp_data=="0": 
    
        extra_data['p_limit']=""
        extra_data['p_limit_c']=False
        
    else:
        temp_data=temp_data.split("*")
        if len(temp_data)==2:
            extra_data['p_limit']=temp_data[1]
            extra_data['p_limit_c']=True
            
        else:
            extra_data['p_limit']=temp_data[0]
            extra_data['p_limit_c']=False
        
    #durum limiti koyma bu dos ataklar ve vs logda kullanilir limit bisi bisi
    temp_data=e.mlimit
    
    if temp_data=="0":
        
        extra_data['limit']=''
        extra_data['d_limit_select']='second'
        extra_data['burst']=''
        
    else:
        temp_data=temp_data.split("*")
        
        if len(temp_data)==2:
            extra_data['burst']=temp_data[0]
            temp_data=temp_data[1].split('/')
            extra_data['limit']=temp_data[0]
            extra_data['d_limit_select']=temp_data[1]
            
        else:
            extra_data['burst']=''
            temp_data=temp_data[0].split('/')
            extra_data['limit']=temp_data[0]
            extra_data['d_limit_select']=temp_data[1]
            
    
    temp_data=e.mac
    
    if temp_data=="0":        
            
    #bir de mac sinirlamasi getirelim
        extra_data['mac']=""
        extra_data['mac_c']=False
        
    else:
        temp_data=temp_data.split("*")
        
        if len(temp_data)==2:
            extra_data['mac']=temp_data[1]
            extra_data['mac_c']=True
            
        else:
            extra_data['mac']=temp_data[0]
            extra_data['mac_c']=False
    
    form=ExtraForm(extra_data)
    
    return render_to_response('add_extra.html', {'form': form,'rule_id':rule_id,'extra_id':e.id})


@login_required
def add_icmp(request,rule_id,icmp_id=None):
    """ That one adds a new icmp entry to the database and also edits the currents one"""
    #control if it is there you may not have a rule like that
    r = get_object_or_404(Rule, pk=rule_id)
    
    if request.method=='GET':
        if r.udp_set.count()!=0 or r.tcp_set.count()!=0 or r.icmp_set.count()!=0:
            request.flash['error']="Udp,Tcp,Icmp sadece bir tane olabilir!"
            return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
    
    if request.method == 'POST':
        
        if icmp_id:
            if r.icmp_set.count()==0:
                request.flash['error']="Olmayan udp editlenemez"
                return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
            
            else:
                
                icmp_edit = get_object_or_404(Icmp,parent_rule=rule_id)
        
        poster=request.POST.copy()
        
            
        form=IcmpForm(poster)
        
        if form.is_valid():
            
            if poster.has_key('icmp_c'):
                icm_value="*".join(['!',poster['icm_tip']])
                
            else:
                icm_value=poster['icm_tip']
            #burada formdan gelen uygun hale getirilecek
            if not icmp_id: 
                i=Icmp(parent_rule_id=rule_id,icmp_type=icm_value)
            else:
                icmp_edit.icmp_type=icm_value
                
            
            try:
                if not icmp_id:
                        
                    i.save()
                
                else:
                    icmp_edit.save()
            
            except Exception,e:
                print "Hata var :",e
                h="Icmp kaydederken hata cikti."
                if not icmp_id:
                    return render_to_response('add_icmp.html', {'form': form,'rule_id':rule_id,'hatalar':h})
                else:
                    return render_to_response('add_icmp.html', {'form': form,'rule_id':rule_id,'hatalar':h,'icmp_id':icmp_id})
            
            #return HttpResponseRedirect(reverse("mysite.iptables.views.index"))
            return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
        
    else:
        form = IcmpForm()
    
    #edit or not
    if not icmp_id:
        #the final render is here...   
        return render_to_response('add_icmp.html', {'form': form,'rule_id':rule_id})
    else:
        return render_to_response('add_icmp.html', {'form': form,'rule_id':rule_id,'icmp_id':icmp_id})
    

@login_required
def edit_icmp(request,rule_id):
    """ Editing the icmp rule we need it ..."""
    
    i = get_object_or_404(Icmp,parent_rule=rule_id)
    
    icmp_data={}
    
    temp_data=i.icmp_type.split('*')
    
    if len(temp_data)==2:
        icmp_data['icmp_c']=True
        icmp_data['icm_tip']=temp_data[1]
        
    else:
        icmp_data['icmp_c']=False
        icmp_data['icm_tip']=temp_data[0]
        
        
    form=IcmpForm(icmp_data)
    
    return render_to_response('add_icmp.html', {'form': form,'rule_id':rule_id,'icmp_id':i.id})


@login_required
def add_prefix(request,rule_id,pref_id=None):
    """ The adding and editing for prefixes"""
    r = get_object_or_404(Rule, pk=rule_id)
    
    if request.method=='GET':
        if r.prefixer_set.count()!=0 :
            request.flash['error']="Kural icin 1 tane log prefixi tanimlanir!"
            return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
    
    if request.method == 'POST':
        
        if pref_id:
            if r.prefixer_set.count()==0:
                request.flash['error']="Olmayan prefix editlenemez"
                return HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
            
            else:
                
                pref_edit = get_object_or_404(Prefixer,parent_rule=rule_id)
        
        poster=request.POST.copy()
        
            
        form=PrefixForm(poster)
        
        if form.is_valid():
            
            if not pref_id:
                 
                i=Prefixer(parent_rule_id=rule_id,pref_name=poster['log_adi'])
            else:
                
                pref_edit.pref_name=poster['log_adi']
                
            
            try:
                if not pref_id:
                        
                    i.save()
                
                else:
                    pref_edit.save()
            
            except Exception,e:
                print "Hata var :",e
                h="Prefix kaydederken hata cikti."
                
                if not pref_id:
                    return render_to_response('add_prefix.html', {'form': form,'rule_id':rule_id,'hatalar':h})
                else:
                    return render_to_response('add_prefix.html', {'form': form,'rule_id':rule_id,'hatalar':h,'pref_id':pref_id})
            
            return  HttpResponseRedirect(reverse(viewname="mysite.iptables.views.rule_edit",args=[rule_id]))
        
        
    else:
        form = PrefixForm()
    
    #edit or not
    if not pref_id:
        #the final render is here...   
        return render_to_response('add_prefix.html', {'form': form,'rule_id':rule_id})
    else:
        return render_to_response('add_prefix.html', {'form': form,'rule_id':rule_id,'pref_id':pref_id})
    
@login_required
def edit_prefix(request,rule_id):
    """ Editing the rule prefix if needed """
    i = get_object_or_404(Prefixer,parent_rule=rule_id)
    
    p_data={}
    p_data['log_adi']=i.pref_name
    
         
    form=PrefixForm(p_data)
    
    return render_to_response('add_prefix.html', {'form': form,'rule_id':rule_id,'pref_id':i.id})

@login_required
def wrap_log(request):
    """ That one is a wrapper for generic Logs"""
    
    #We neeed to update the logs everytime not sure if it is efficent 
    l=Logman()
    l.genLine()
    
    if request.method== 'POST':
        if request.session.get('filterman'):
            #print "Postta sil ",request.session['filterman']
            del request.session['filterman']
                        
        if request.session.get('wordman'):
            #print "Postta sil ",request.session['wordman']
            del request.session['wordman']
                
        #burda bisiler yap
        poster=MultiValueDict({'kelime': [request['kelime']], 'kriter': [request['kriter']]})
        form=LogSearchForm(poster)
        
        
        #print request['kelime']
        if form.is_valid():
            
            if request.has_key('kriter'):
                
                
                sorgu=FireUtils.generate_log_query(request['kriter'],request['kelime'])
                
                if sorgu :
                    
                    request.session['filterman']=request['kriter']
                    
                    if request['kelime']!='':
                        request.session['wordman']=request['kelime']
                        
                
                #form=LogSearchForm()
                
                params={
                
                    'queryset':sorgu,
                    'paginate_by':10,
                    'template_name':'log_table.html',
                    'extra_context':{
                                'form':form
                                    },   
            
                                    }
                #print params['extra_context']
                return object_list(request,**params)
                
                
                
                    
                
        else : #the form is not valid
            
            sorgu=Logs.objects.filter(outDev__icontains="makkalot")
                        
            #print form
            
            params={
                
            'queryset':sorgu,
            'paginate_by':10,
            'template_name':'log_table.html',
            'extra_context':{
                            'form':form
                            },   
                }
            
            #print params['extra_context']
            return object_list(request,**params)            
                
            
    else:        
        if request.session.get('filterman'):    
            #we have something before
            w_topass=""
            if request.session.get('wordman'):
                #to see if we also have a search word
                w_topass=request.session['wordman']
                
            #print "Get icinde :",request.session['filterman'],w_topass    
            sorgu=FireUtils.generate_log_query(request.session['filterman'],w_topass)
            
        else:
            sorgu=Logs.objects.order_by('-log_date')
            
        form=LogSearchForm()
            #demek ki linkte geldik sadece
        
        #print form
        
        params={
                    
                'queryset':sorgu,
                'paginate_by':10,
                'template_name':'log_table.html',
                'extra_context':{
                                'form':form
                                },  
                    
                    }
           
        #print params['extra_context']
        return object_list(request,**params)
    

@login_required
def show_load(request,chain_id=None):
    """ Shows the rules by categorizinggg"""
    if not chain_id:
        initial=Chain.objects.filter(name="INPUT")
        if not initial:
            return render_to_response('index.html')
        
        chain_id=initial[0].id
    
    #bu degiscek dur
    sor=Rule.objects.filter(parent_chain=chain_id,loaded=True)
    #buradan loadindexe göre sıralatmak lazım 
    
    sorgu=Loadindex.objects.filter(parent_rule__in=[s.id for s in sor]).order_by('ordering')
    
    chain=Chain.objects.all()
    
    params={
                    
                'queryset':sorgu,
                'paginate_by':6,
                'template_name':'another_table.html',
                'extra_context':{
                                 'chain':chain
                                 }
                    }
            
    return object_list(request,**params)

@login_required
def load_rule(request):
    """ When it is pressed on HAYIR"""
    if request.method== 'POST':
        
        try:
            id=int(request.POST['loader'])
            ch=int(request.POST['chain'])
        
        except ValueError:
            return render_to_response('index.html')
        
        r=RuleLoadOrder()
        r.insert_order(str(id),ordernum='last')
        
        return  HttpResponseRedirect(reverse(viewname="mysite.iptables.views.show_load",args=[ch]))
    
    else:
        
        return  HttpResponseRedirect(reverse(viewname="mysite.iptables.views.index"))
        
        
    
@login_required
def unload_rule(request):
    """ When it is pressed on HAYIR"""
    
    if request.method== 'POST':
        
        try:
            id=int(request.POST['loader'])
            ch=int(request.POST['chain'])
        
        except ValueError:
            return render_to_response('index.html')
    
        r = get_object_or_404(Rule,id=id)
        
        r.loaded=False
        r.save()
        #r.delete_order(id)
        
        return  HttpResponseRedirect(reverse(viewname="mysite.iptables.views.show_load",args=[ch]))
    
    else:
        return  HttpResponseRedirect(reverse(viewname="mysite.iptables.views.index"))
    

@login_required
def add_chain(request,chain_id=None):
    """ adding chains to the system"""
    
    if request.method == 'POST':
        
        if chain_id:
            chain_edit = get_object_or_404(Chain,id=chain_id)
            
        poster=request.POST.copy()
        
        form=ChainForm(poster)
        
        if form.is_valid():
            
            if not chain_id: 
                chain=Chain(name=form.cleaned_data['isim'].strip(),description=form.cleaned_data['aciklama'].strip())
            else:
                chain_edit.name=form.cleaned_data['isim'].strip()
                chain_edit.description=form.cleaned_data['aciklama'].strip()
            
            try:
                if not chain_id:
                        
                    chain.save()
                
                else:
                    chain_edit.save()
            
            except Exception,e:
                #print "Hata var :",e
                h="Chain kaydederken hata cikti."
                if not chain_id:
                    return render_to_response('add_chain.html', {'form': form,'hatalar':h})
                else:
                    return render_to_response('add_chain.html', {'form': form,'chain_id':chain_id,'hatalar':h})
            
            #return HttpResponseRedirect(reverse("mysite.iptables.views.index"))
            return HttpResponseRedirect(reverse("mysite.iptables.views.show_chains"))
            
    else:
        form = ChainForm()
    
    #edit or not
    if not chain_id:
        return render_to_response('add_chain.html', {'form': form})
    else:
        return render_to_response('add_chain.html', {'form': form,'chain_id':chain_id})
            
    
@login_required
def edit_chain(request,chain_id):
    """ Editing the chains thing"""
    chain = get_object_or_404(Chain,id=chain_id)
    
    chain_data={}
    chain_data['isim']=chain.name
    chain_data['aciklama']=chain.description
    
    form=ChainForm(chain_data)
    
    return render_to_response('add_chain.html', {'form': form,'chain_id':chain_id})
    

@login_required
def order_up(request):
    """ When it is pressed on UP arrow"""
    
    if request.method== 'POST':
        
        try:
            id=int(request.POST['rule_id'])
            ch=int(request.POST['chain'])
        
        except ValueError:
            return render_to_response('index.html')
    
        l = get_object_or_404(Loadindex,parent_rule=id)
        
        #get the smaller ones
        brothers=Loadindex.objects.filter(ordering__lt=l.ordering).order_by('-ordering')
        #r.delete_order(id)
        
        if not brothers:
            return  HttpResponseRedirect(reverse(viewname="mysite.iptables.views.show_load",args=[ch]))
            
        for loader in brothers:
            if loader.parent_rule.parent_chain.name==l.parent_rule.parent_chain.name:
                #exchange them
                r_order=RuleLoadOrder()
                #print "First swap parameter is ",loader.id
                #print "second swap parameter is ",l.id
                r_order.swap_order(loader.parent_rule.id,l.parent_rule.id,chain_name=l.parent_rule.parent_chain.name)
                
                break
                
        return  HttpResponseRedirect(reverse(viewname="mysite.iptables.views.show_load",args=[ch]))
    
    else:
        return  HttpResponseRedirect(reverse(viewname="mysite.iptables.views.index"))
        

@login_required
def order_down(request):
    """ When it is pressed on DOWN arrow
    pff i'm lazy to make them a method :) dont have time"""
    
    if request.method== 'POST':
        
        try:
            id=int(request.POST['rule_id'])
            ch=int(request.POST['chain'])
        
        except ValueError:
            return render_to_response('index.html')
    
        l = get_object_or_404(Loadindex,parent_rule=id)
        
        #get the smaller ones -ordering once buyukleri siralar unutma bunu genc...
        biggers=Loadindex.objects.filter(ordering__gt=l.ordering).order_by('ordering')
        #r.delete_order(id)
        
        if not biggers:
            return  HttpResponseRedirect(reverse(viewname="mysite.iptables.views.show_load",args=[ch]))
            
        for loader in biggers:
            if loader.parent_rule.parent_chain.name==l.parent_rule.parent_chain.name:
                #exchange them
                #print "First swap parameter is ",loader.id
                #print "second swap parameter is ",l.id
                
                r_order=RuleLoadOrder()
                r_order.swap_order(l.parent_rule.id,loader.parent_rule.id,chain_name=l.parent_rule.parent_chain.name)
                
                break
                
        return  HttpResponseRedirect(reverse(viewname="mysite.iptables.views.show_load",args=[ch]))
    
    else:
        return  HttpResponseRedirect(reverse(viewname="mysite.iptables.views.index"))


@login_required
def show_chains(request):
    """ Shows the chains that are added manually"""
    
    sorgu=Chain.objects.all()
    
    params={
                    
                'queryset':sorgu,
                'paginate_by':6,
                'template_name':'chain_table.html',
                    }
            
    return object_list(request,**params)
    

@login_required
def show_sort_chains(request,chain_name=None):
    """ Shows the chains that are added manually"""
    
    #if not chain_name:
        #chain_name="INPUT"
    sorgu= Rule.objects.all()
    #print chain_name
    
    if not chain_name:
        ch=Chain.objects.filter(name=chain_name)
        if ch:
            sorgu= Rule.objects.filter(parent_chain=ch[0].id)
        
    
    params={
                    
                'queryset':sorgu,
                'paginate_by':6,
                'template_name':'rule_table.html',
                    }
            
    return object_list(request,**params)
